// 实现这个项目的构建任务
// gulp 的入口文件
const { src, dest, parallel, series, watch } = require('gulp')
const del = require('del') // 引用gulp删除插件
const browserSync = require('browser-sync') // 引用实时预览浏览器

const loadPlugins = require('gulp-load-plugins')
const plugins = loadPlugins()
// 创建开发服务
const bs = browserSync.create()

// html 页面
const data = {
  menus: [
    {
      name: 'Home',
      line: 'index.html'
    },
    {
      name: 'About',
      link: 'about.html'
    }
  ],
  pkg: require('./package.json'),
  date: new Date()
}

// 清除掉之前打包好的dist和temp文件
const clean = () => {
  return del([ 'dist', 'temp' ])
}

// 打包样式文件
const style = () => {
  return src('src/assets/styles/*.scss', { base: 'src' })
    .pipe(plugins.sass({ outputStyle: 'expanded' }))
    .pipe(dest('temp'))
    .pipe(bs.reload({ stream: true }))
}

// 打包 html 文件
const pages = () => {
  return src('src/*.html')
    .pipe(plugins.swig({ data, defaults: { cache: false } }))  // 防止缓存
    .pipe(dest('temp'))
    .pipe(bs.reload({ stream: true }))
}

// 打包 js 文件
const script = () => {
  return src('src/assets/scripts/*.js', { base: 'src' })
    .pipe(plugins.babel({ presets: ['@babel/preset-env'] }))
    .pipe(dest('temp'))
    .pipe(bs.reload({ stream: true }))
}

// 压缩 image
const image = () => {
  return src('src/assets/images/**', { base: 'src' })
    .pipe(plugins.imagemin())
    .pipe(dest('dist'))
}

// 压缩字体文字
const font = () => {
  return src('src/assets/fonts/**', { base: 'src' })
    .pipe(plugins.imagemin())
    .pipe(dest('dist'))
}

const extra = () => {
  return src('public/**', { base: 'public' })
    .pipe(dest('dist'))
}

// 对现有文件进行lint检测
const lintTask = () => {
  return src('src/assets/scripts/*.js', { base: 'src' })
    .pipe(plugins.eslint())
}

// 运行当前项目
const serve = () => {
  watch('src/assets/styles/*.scss', style)
  watch('src/assets/scripts/*.js', script)
  watch('src/*.html', pages)

  watch([
    'scr/assets/images/**',
    'scr/assets/fonts/**',
    'public/**'
  ], bs.reload)

  bs.init({
    notify: false,
    port: 2080,
    server: {
      baseDir: ['temp', 'src', 'public'],
      routes: {
        '/node_modules': 'node_modules'
      }
    }
  })
}

const useref = () => {
  return src('temp/*.html', { base: 'temp' })
    .pipe(plugins.useref({ searchPath: ['temp', '.'] }))
    // html js css
    .pipe(plugins.if(/\.js$/, plugins.uglify()))
    .pipe(plugins.if(/\.css$/, plugins.cleanCss()))
    .pipe(plugins.if(/\.html$/, plugins.htmlmin({
      collapseWhitespace: true,
      minifyCSS: true,
      minifyJS: true
    })))
    .pipe(dest('dist'))
}

const compile = parallel(style, script, pages)

// 打包任务
const build = series(
  clean,
  parallel(
    series(compile, useref),
    image,
    font,
    extra
  )
)

const start = () => {}

const lint = series(lintTask)

const deploy = series(compile, serve)

module.exports = {
  clean,
  lint,
  serve,
  build,
  start,
  deploy
}
